package com.sky.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.sky.constant.MessageConstant;
import com.sky.dto.UserLoginDTO;
import com.sky.entity.User;
import com.sky.exception.LoginFailedException;
import com.sky.mapper.UserMapper;
import com.sky.properties.WeChatProperties;
import com.sky.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.sky.utils.HttpClientUtil;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;

@Service
@Slf4j
public class UserServiceImpl implements UserService {
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private WeChatProperties weChatProperties;
    //微信服务接口地址
    public static final String WX_LOGIN = "https://api.weixin.qq.com/sns/jscode2session";

    /**
     * 微信登录
     * @param userLoginDTO
     * @return
     */
    @Override
    public User wxLogin(UserLoginDTO userLoginDTO) {
        //通过userLoginDTO获取open_id
        String openId = getOpenId(userLoginDTO.getCode());
        //直接判定openId 如果openId为null 则抛出登录异常
        if(openId == null)
        {
            throw new LoginFailedException(MessageConstant.LOGIN_FAILED);
        }
        //通过open_id查询数据库，如果存在则返回用户信息，如果不存在则创建用户并返回用户信息
        User user = userMapper.selectByOpenId(openId);
        if(user == null){
            user = User.builder()
                    .openid(openId)
                    .createTime(LocalDateTime.now())
                    .build();
            //用户表新增一条记录
            userMapper.insert(user);
        }
        //返回这个用户对象
        return user;
    }

    /**
     * 调用微信接口服务获取登录用户的open_id
     * @param code
     * @return
     */
    public String getOpenId(String code){
        //通过拼接appid,secret,jscode,grant_type发送请求获取openId
        //构建请求体
        Map<String, String> map = new HashMap<>();
        map.put("appid",weChatProperties.getAppid());
        map.put("secret",weChatProperties.getSecret());
        map.put("js_code",code);
        map.put("grant_type","authorization_code");
        
        log.info("调用微信API获取openid，参数：appid={}, code={}", weChatProperties.getAppid(), code);
        
        try {
            //通过自定义工具类发送请求
            String json = HttpClientUtil.doGet(WX_LOGIN, map);
            log.info("微信API响应：{}", json);
            
            if (json == null || json.trim().isEmpty()) {
                log.error("微信API返回空响应");
                return null;
            }
            
            JSONObject jsonObject = JSON.parseObject(json);
            
            // 检查是否有错误码
            if (jsonObject.containsKey("errcode")) {
                Integer errcode = jsonObject.getInteger("errcode");
                String errmsg = jsonObject.getString("errmsg");
                log.error("微信API返回错误：errcode={}, errmsg={}", errcode, errmsg);
                return null;
            }
            
            String openid = jsonObject.getString("openid");
            log.info("成功获取openid：{}", openid);
            return openid;
            
        } catch (Exception e) {
            log.error("调用微信API异常", e);
            return null;
        }
    }
}
